REMOVING DUPLICATE LINES

As a second example, here is a script for removing duplicate lines from a text.

#!lua
local used = { }empty table
for linevariable: you choose its namein ioinput/output library.table memberlines( arg[1]the textfile ) do
  if not used[line]table accessthen
    print (line)
    used[line] table access = true
  end -- if
end -- for

The expression { } denotes a new empty table. In line 4 the value of this table at the value of line is negated by the operator not. If the table has no entry for this value of line, i.e. the value nil, then the body of the if-block, lines 5 and 6, is executed. In line 5 the line of text is output. In line 6 the table is given the Boolean value true at the current line. So only lines of text that have not previously occurred get output.

There are two new points here. The first is the use of tables, which resemble arrays but do not have to be indexed by numbers. Tables can be indexed by any non-nil type of value. Here they are indexed by strings. The second is that variables which have not been assigned any value are deemed to have the value nil, which is treated as false for the purposes of conditionals. All other non-Boolean values are treated as true.

Tables are rather like functions of one variable. Instead of arguments (with round brackets) one speaks of indices or keys (with square brackets). They return nil for all indices except those that have been defined. Unlike functions, no evaluation is required, only lookup. So functions take up time but save on space, tables take up space but save on time.